package com.sczmgk.track.base;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.sczmgk.track.R;
import com.sczmgk.track.constant.Constant;
import com.sczmgk.track.dialog.DialogFactory;
import com.sczmgk.track.dialog.MessageDialog;
import com.sczmgk.track.interf.ActivityCallback;
import com.sczmgk.track.popup.PupDialog;
import com.sczmgk.track.receiver.ListenNetStateReceiver;
import com.sczmgk.track.utils.CommonUtils;
import com.sczmgk.track.utils.Tools;
import com.sczmgk.track.view.MyHeadView;

import java.util.List;

public abstract class BaseActivity extends AppCompatActivity implements ActivityCallback {

    protected boolean isConnected = true;

    protected final int REFRESH_NET = 2001;
    protected FrameLayout videoView;
    protected String TAG = this.getClass().getSimpleName();
    private Dialog loadingDialog;
    /**
     * 自定义title
     */
    private MyHeadView mHeadView;

    private MessageDialog successDialog;
    private MessageDialog errorDialog;
    private DrawerLayout mDrawerLayout;
    private RelativeLayout mRlLeftLayout;

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

    /**
     * 界面容器
     */
    protected FrameLayout mLinearLayoutContent;

    private LayoutInflater mLayoutInflater;
    /**
     * base布局
     */
    public View baseLayout;
    /**
     * 底部弹出框的 引用
     */
    public PupDialog menuWindow = null;
    public PopupWindow sharePup = null;
    protected Handler mHandler = null;

    //    @SuppressLint("HandlerLeak")
    private void initHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case Constant.ON_ERROR_CODE_ERROR_MSG:
                        String errorMsg = (String) msg.obj;
                        if (errorDialog == null) {
                            showDialog(errorMsg);
                        } else if (!errorDialog.isShowing()) {
                            showDialog(errorMsg);
                        }
                        break;
                    case Constant.ON_LOAD_SUCCESS:
                        int res = (int) msg.obj;
                        if (successDialog == null) {
                            showSuccDialog(res);
                        } else if (!successDialog.isShowing()) {
                            showSuccDialog(res);
                        }
                        break;
                }
                BaseActivity.this.handleMessage(msg);
            }
        };
    }

    public abstract void handleMessage(Message msg);

    /**
     * @param pupid    弹出框的 id
     * @param pupEvent 弹出框 按钮的监听事件接口
     */
    @Override
    public void showPup(String pupid, PupDialog.PupEvent pupEvent) {
        dismissPup();
        menuWindow = new PupDialog(this, pupid, pupEvent);

        menuWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 显示窗口
        menuWindow.showAtLocation(baseLayout, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void dismissPup() {
        if (null != menuWindow && menuWindow.isShowing()) {
            menuWindow.dismiss();
        }
    }


    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        requestWindowFeature(Window.FEATURE_NO_TITLE);

//        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            setTranslucentStatus(true);
//            SystemBarTintManager tintManager = new SystemBarTintManager(this);
//            tintManager.setStatusBarTintEnabled(true);
//            tintManager.setStatusBarTintResource(R.color.sc_transparent_background);//通知栏所需颜色
//        }
        super.setContentView(R.layout.layout_include_title);
        initHandler();
        mLayoutInflater = LayoutInflater.from(this);

        mHeadView = (MyHeadView) findViewById(R.id.headview);
        videoView = (FrameLayout) findViewById(R.id.fl_video_view);
        mHeadView.setLeftBtnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onLeftButtonClick();
            }
        });
        mHeadView.setRightBtnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onRightButtonClick();
            }
        });

        mDrawerLayout = (DrawerLayout) findViewById(R.id.dl_drawer_layout);
        mDrawerLayout.setScrimColor(Color.TRANSPARENT);

        if (!isLockLeft()) {
            //禁止侧边滑动
            mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        }

        mRlLeftLayout = (RelativeLayout) findViewById(R.id.rl_main_left_drawer_layout);

        mHeadView.setNextRightBtnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onNextRightButtonClick();
            }
        });

        mLinearLayoutContent = (FrameLayout) findViewById(R.id.main_home_container);
        baseLayout = findViewById(R.id.layout_base);
        mHeadView.setLeftCloseBtnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        isConnected = CommonUtils.isNetworkAvailable(BaseActivity.this);
        ListenNetStateReceiver.OnNetWorkChangedListener callback = new ListenNetStateReceiver.OnNetWorkChangedListener() {
            @Override
            public void onDisconnected() {
                isConnected = false;
                mHandler.sendEmptyMessage(REFRESH_NET);
            }

            @Override
            public void onConnedted() {
                isConnected = true;
                mHandler.sendEmptyMessage(REFRESH_NET);
            }
        };
        ListenNetStateReceiver.onNetWorkChangedListener = callback;

    }

    public boolean isLockLeft() {
        return false;
    }


    //左边菜单开关事件
    public void openLeftLayout() {
        if (mDrawerLayout.isDrawerOpen(mRlLeftLayout)) {
            mDrawerLayout.closeDrawer(mRlLeftLayout);
        } else {
            mDrawerLayout.openDrawer(mRlLeftLayout);
        }
    }

    public void isShowLeftView(final boolean isShowLeft){
        mRlLeftLayout.setVisibility(isShowLeft ? View.VISIBLE : View.GONE);
        setLeftBtnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isShowLeft){
                    openLeftLayout();
                }else {
                    finish();
                }
            }
        });
    }

    protected void onRightButtonClick() {

    }


    private void onNextRightButtonClick() {

    }


    protected void onLeftButtonClick() {
        finish();
    }

    public void goneHeadView() {
        mHeadView.setVisibility(View.GONE);
    }

    @Override
    public void visibleHeadView() {
        mHeadView.setVisibility(View.VISIBLE);
    }

    public int getLeftBtnBGResource() {
        return mHeadView.getLeftBtnBGResource();
    }

    @Override
    public void setLeftBtnEnabled(boolean enabled) {
        mHeadView.getBtnLeft().setEnabled(enabled);
    }

    @Override
    public void setLeftBtnVisibility(int visible) {
        mHeadView.setLeftBtnVisibility(visible);
    }

    @Override
    public void setLeftBtnBackground(int resource) {
        mHeadView.setLeftBtnBackground(resource, -1);
    }

    @Override
    public void setLeftBtnBackground(int resource, int text) {
        mHeadView.setLeftBtnBackground(resource, text);
    }

    @Override
    public void setLeftBtnBackground(int resource, int text, int textColorResource) {
        mHeadView.setLeftBtnBackground(resource, text, textColorResource);
    }

    @Override
    public void setLeftBtnTextColor(int textColorResource) {
        mHeadView.setLeftBtnTextColor(textColorResource);
    }

    @Override
    public void setLeftBtnText(String text) {
        mHeadView.setLeftBtnText(text);
    }

    @Override
    public void setLeftBtnClickListener(OnClickListener listener) {
        mHeadView.setLeftBtnClickListener(listener);
    }

    @Override
    public void setRightBtnEnabled(boolean enabled) {
        mHeadView.getBtnRight().setEnabled(enabled);
    }

    @Override
    public void setRightBtnVisibility(int visible) {
        mHeadView.setRightBtnVisibility(visible);
    }

    @Override
    public void setRightBtnBackground(int resource) {
        mHeadView.setRightBtnBackground(resource, -1);
    }

    @Override
    public void setRightBtnDescription(String desc) {
        mHeadView.setRightBtnDesc(desc);
    }

    @Override
    public void setRightBtnBackground(int resource, int text) {
        mHeadView.setRightBtnBackground(resource, text);
    }

    public void setRightBtnBackground(int resource, String text) {
        mHeadView.setRightBtnBackground(resource, text);
    }

    @Override
    public void setRightBtnBackground(int resource, int text, int textColorResource) {
        mHeadView.setRightBtnBackground(resource, text, textColorResource);
    }

    @Override
    public void setRightBtnTextColor(int textColorResource) {
        mHeadView.setRightBtnTextColor(textColorResource);
    }

    @Override
    public void setRightBtnText(int resid) {
        mHeadView.setRightBtnText(resid);
    }

    @Override
    public void setRightBtnClickListener(OnClickListener listener) {
        mHeadView.setRightBtnClickListener(listener);
    }

    public int getRightBtnBGResource() {
        return mHeadView.getRightBtnBGResource();
    }

    @Override
    public void setTitleIcon(int resource) {
        mHeadView.setTitleIcon(resource);
    }

    @Override
    public void setTitle(int resource) {
        if (resource > 0) {
            mHeadView.setTitle(resource);
        }
    }

    @Override
    public void setTitle(String title) {
        if (!Tools.isEmpty(title)) {
            mHeadView.setTitle(title);
        }
    }

    @Override
    public void setTitleColor(int color) {
        mHeadView.setTitleColor(color);
    }

    @Override
    public void setNextRightBtnEnabled(boolean enabled) {
        mHeadView.getBtnRight().setEnabled(enabled);
    }

    @Override
    public void setNextRightBtnVisibility(int visible) {
        mHeadView.setNextRightBtnVisibility(visible);
    }

    @Override
    public void setNextRightBtnBackground(int resource) {
        mHeadView.setNextRightBtnBackground(resource, -1);
    }

    @Override
    public void setNextRightBtnDescription(String desc) {
        mHeadView.setNextRightBtnDesc(desc);
    }

    @Override
    public void setNextRightBtnBackground(int resource, int text) {
        mHeadView.setNextRightBtnBackground(resource, text);
    }

    public void setNextRightBtnBackground(int resource, String text) {
        mHeadView.setRightBtnBackground(resource, text);
    }

    @Override
    public void setNextRightBtnBackground(int resource, int text, int textColorResource) {
        mHeadView.setNextRightBtnBackground(resource, text, textColorResource);
    }

    @Override
    public void setNextRightBtnTextColor(int textColorResource) {
        mHeadView.setNextRightBtnTextColor(textColorResource);
    }

    @Override
    public void setNextRightBtnText(int resid) {
        mHeadView.setNextRightBtnText(resid);
    }

    @Override
    public void setNextRightBtnClickListener(OnClickListener listener) {
        mHeadView.setNextRightBtnClickListener(listener);
    }

    //TODO 分享按钮的点击事件
    public void setShareBtnClickListener(OnClickListener listener) {
        mHeadView.setShareBtnClickListener(listener);
    }

    //TODO 分享按钮的显示
    public void setShareBtnVisiable(int visible) {
        mHeadView.setShareBtnVisibility(visible);
    }

    //TODO 分享按钮的北京
    public void setShareBtnBGResource(int res) {
        mHeadView.setShareBtnBackground(res);
    }

    public int getNextRightBtnBGResource() {
        return mHeadView.getNextRightBtnBGResource();
    }

    public void setTitleIconText(int res) {
        mHeadView.setTitleIconText(res);
    }

    public void setTitleIconText(String res) {
        mHeadView.setTitleIconText(res);
    }

    public void setTitleIconClick(OnClickListener listener) {
        mHeadView.setTitleIconClick(listener);
    }

    public void setTitleIconVisiable(int visiable) {
        mHeadView.setTitleIconVisiable(visiable);
    }


    public void setRightTitleText(String text) {
        mHeadView.setTitleText(text);
    }

    public void setRightTitleText(int res) {
        mHeadView.setTitleText(res);
    }

    public void setRightTitleClick(OnClickListener listener) {
        mHeadView.setTitleClick(listener);
    }

    public void setRightTitleClickListener(OnClickListener listener) {
        mHeadView.setRightTitleClickListener(listener);
    }

    public void setRightTitleVisiable(int visiable) {
        mHeadView.setTitleVisiable(visiable);
    }


    @Override
    public void setHeadBackgroudColor(int color) {
        mHeadView.setHeadBackground(color);
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = mLayoutInflater.inflate(layoutResID, null);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        mLinearLayoutContent.removeAllViews();
        mLinearLayoutContent.addView(view, lp);
    }

    @Override
    public void setContentView(View view, LayoutParams params) {
        mLinearLayoutContent.removeAllViews();
        mLinearLayoutContent.addView(view, params);
    }

    @Override
    public void setContentView(View view) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        mLinearLayoutContent.removeAllViews();
        mLinearLayoutContent.addView(view, lp);
    }

    protected int getContendId() {
        return R.id.main_home_container;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    protected void showFragment(int resId, Fragment fragment) {
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (getIsNeedLogin()) {
//            boolean isLogin = CacheUtils.getLoginStatus(BaseActivity.this);
//            if (!isLogin) {
//                finish();
//            }
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismissLoadingDiaLog();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public MyHeadView getHeadView() {
        return mHeadView;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent arg2) {
        super.onActivityResult(requestCode, resultCode, arg2);

        switch (requestCode) {

        }
    }

    public void cancelTask(List<AsyncTask<?, ?, ?>> tasks) {
        if (tasks == null || tasks.size() == 0) {
            return;
        }

        for (AsyncTask<?, ?, ?> task : tasks) {
            if (task != null && AsyncTask.Status.RUNNING == task.getStatus()) {
                task.cancel(true);
            }
        }
    }

    @Override
    public void setHeadViewVisibility(int visible) {
        mHeadView.setVisibility(visible);
    }

    public void setLeftCloseBtnVisibility(int visible) {
        mHeadView.setLeftCloseBtnVisibility(visible);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            finish();
            return true;

        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    public void setCustomVideoView(View view) {
        videoView.setVisibility(View.VISIBLE);
        videoView.addView(view);
    }

    public void hidecustomVideoView() {
        videoView.removeAllViews();
        videoView.setVisibility(View.GONE);
    }


    protected void showLoadingDiaLog() {
        DialogFactory.dismissLoadingDialog(BaseActivity.this, loadingDialog);
        if (loadingDialog == null) {
            loadingDialog = DialogFactory.getLoadingDialog(BaseActivity.this, R.string.dialog_loading);
        }
        DialogFactory.showDialog(BaseActivity.this, loadingDialog);
    }

    protected void dismissLoadingDiaLog() {
        DialogFactory.dismissLoadingDialog(BaseActivity.this, loadingDialog);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    public void showErrorMsg(String msg) {
        Message message = Message.obtain();
        message.what = Constant.ON_ERROR_CODE_ERROR_MSG;
        message.obj = msg;
        mHandler.sendMessage(message);
    }

    public void showSuccessDialog(int res) {
        Message message = Message.obtain();
        message.what = Constant.ON_LOAD_SUCCESS;
        message.obj = res;
        mHandler.sendMessage(message);
    }

    private void showSuccDialog(int res) {
        successDialog = DialogFactory.warningDialog(BaseActivity.this, getResources().getString(res), R.string.sure, new OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void showDialog(String errorMsg) {
        errorDialog = DialogFactory.warningDialog(BaseActivity.this, errorMsg, R.string.back, new OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
    }
}
